package com.mxx.common.security;

import com.mxx.common.utils.RandomUtil;
import com.mxx.common.utils.Strings;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Optional;

/**
 * @Author itzgyw
 * @Date 2020-03-20
 * @Time 15:49
 * @Description:
 */
public class DESPkcs7Util {
    private static final String ALGORITHM_DES = "DES/CBC/PKCS7Padding";

    static {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    public static Optional<String> getIV() {
        try {
            SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
            String str = RandomUtil.randomNumber(8).toLowerCase();
            byte[] ivByte = str.getBytes(StandardCharsets.UTF_8);
            randomSecureRandom.nextBytes(ivByte);
            IvParameterSpec ivParams = new IvParameterSpec(ivByte);
            String iv = Strings.encodeToStr(ivParams.getIV());
            return Optional.of(iv);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Optional.empty();
        }
    }

    //获取加密或解密的Cipher对象：负责完成加密或解密工作
    private static Cipher GetCipher(int model, byte[] key, byte[] iv) {
        try {
            //根据传入的秘钥内容生成符合DES加密解密格式的秘钥内容
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
            DESKeySpec dks = new DESKeySpec(key);
            //获取DES秘钥生成器对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // 生成秘钥：key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            //获取DES/ECB/PKCS7Padding该种级别的加解密对象
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            //初始化加解密对象【opmode:确定是加密还是解密模式；secretKey是加密解密所用秘钥】
            cipher.init(model, secretKey, ivParameterSpec);
            return cipher;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * DES算法，加密
     *
     * @param data 待加密字符串
     * @param key  加密私钥，长度不能够小于8位
     * @return 加密后的字节数组，一般结合Base64编码使用
     * @throws Exception
     */
    public static Optional<String> encode(String data, String key, String iv) {
        if (data == null || data.isEmpty())
            return null;
        try {
            byte[] keyByte = Strings.decode(key);
            byte[] ivByte = Strings.decode(iv);


            //获取加密对象【Cipher.ENCRYPT_MODE：指定加密模式为1】
            Cipher cipher = GetCipher(Cipher.ENCRYPT_MODE, keyByte, ivByte);
            if (cipher == null) {
                return Optional.empty();
            } else {
                //设置加密的字符串为utf-8模式并且加密，返回加密后的byte数组。
                byte[] byteHex = cipher.doFinal(Strings.toByte(data));
                return Optional.of(Strings.encodeToStr(byteHex));//对加密后的数组进制转换
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }

    /**
     * DES算法，解密
     *
     * @param data 待解密字符串
     * @param key  解密私钥，长度不能够小于8位
     * @return 解密后的字节数组
     * @throws Exception
     * @throws Exception 异常
     */
    public static Optional<String> decode(String data, String key, String iv) {
        if (data == null || data.isEmpty())
            return Optional.empty();
        try {
            byte[] keyByte = Strings.decode(key);
            byte[] ivByte = Strings.decode(iv);

            //先把待解密的字符串转成Char数组类型，然后进行进制转换。
            byte[] b = Strings.decode(data);
            //获取解密对象【Cipher.DECRYPT_MODE：指定解密模式为2】
            Cipher cipher = GetCipher(Cipher.DECRYPT_MODE, keyByte, ivByte);
            if (cipher != null)
                //进行解密返回utf-8类型的字符串
                return Optional.of(Strings.toString(cipher.doFinal(b)));
            else
                return Optional.empty();
        } catch (Exception e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }


}
